package com.yy.invoice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.invoice.config.QiuNiuYunConfig;
import com.yy.invoice.entity.Invoice;
import com.yy.invoice.entity.Result;
import com.yy.invoice.entity.User;
import com.yy.invoice.mapper.InvoiceMapper;
import com.yy.invoice.mapper.UserMapper;
import com.yy.invoice.service.InvoiceService;
import com.yy.invoice.utils.FileUtils;
import com.yy.invoice.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yang1yu
 * @since 2022-09-27
 */
@Service
@Slf4j
public class InvoiceServiceImpl extends ServiceImpl<InvoiceMapper, Invoice> implements InvoiceService {

    @Autowired
    private InvoiceMapper invoiceMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private QiuNiuYunConfig qiuNiuYunConfig;
    @Override
    public Result select(HttpServletRequest request) {
        Result result = new Result();
        try {
            List<Invoice> invoices = invoiceMapper.selectList(
                    new QueryWrapper<Invoice>()
                            .like("upload_time", new SimpleDateFormat("yyyy-MM").format(new Date()))
                            .eq("user_id", JwtUtil.parseJWT(request.getHeader("token")).getSubject())
                            .orderByAsc("total_amount * 1")
            );
            result.setMessage("success");
            result.setCode(0);
            result.setData(invoices);
        } catch (Exception e) {
            result.setMessage("error");
            result.setCode(1);
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    public Result selectByMonth(String month, HttpServletRequest request) {
        Result result = new Result();
        try {
            List<Invoice> invoices = invoiceMapper.selectList(
                    new QueryWrapper<Invoice>()
                            .eq("user_id", JwtUtil.parseJWT(request.getHeader("token")).getSubject())
                            .like("upload_time", month)
                            .orderByAsc("total_amount * 1")
            );
            result.setData(invoices);
            result.setMessage("success");
            result.setCode(0);
        } catch (Exception e) {
            result.setMessage("error");
            result.setCode(1);
            throw new RuntimeException(e);
        }

        return result;
    }

    @Override
    public Result sumByMonth(String month, HttpServletRequest request) {
        Result result = new Result();
        try {
            String userId = JwtUtil.parseJWT(request.getHeader("token")).getSubject();
            List<Invoice> invoices = invoiceMapper.selectList(new LambdaQueryWrapper<Invoice>().eq(Invoice::getUserId, userId).like(Invoice::getUploadTime, month));
            BigDecimal add = new BigDecimal("0.0");
            for (Invoice invoice : invoices) {
                add = add.add(new BigDecimal(invoice.getTotalAmount()));
            }
            result.setCode(0);
            result.setMessage("success");
            HashMap<Object, Object> map = new HashMap<>();
            map.put("totalAmount",add);
//            result.setData("{\"totalAmount\":\"" + add + "\"}");
            result.setData(map);
        } catch (Exception e) {
            result.setMessage("error");
            result.setCode(1);
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    public Result delete(List<Invoice> invoices, HttpServletRequest request) {
        Result result = new Result();
        int status = 0;
        try {
            for (Invoice invoice : invoices) {
                int delete = invoiceMapper.delete(
                        new LambdaQueryWrapper<Invoice>()
                                .eq(Invoice::getInvoiceCode, invoice.getInvoiceCode())
                                .eq(Invoice::getInvoiceNum, invoice.getInvoiceNum())
                                .eq(Invoice::getUserId, JwtUtil.parseJWT(request.getHeader("token")).getSubject())
                );
                if (delete != 1){
                    status += 1;
                }
            }
            result.setMessage("delete success");
            result.setCode(status);
        } catch (Exception e) {
            result.setMessage("delete error");
            result.setCode(status);
            throw new RuntimeException(e);
        }
        return result;
    }



    @Override
    public Result updateInvoice(String invoiceCode, String invoiceNum, String validate, String totalAmount, Integer invoiceId) {
        Result result = new Result();
        Invoice invoice = new Invoice();
        invoice.setInvoiceId(invoiceId);
        invoice.setInvoiceCode(invoiceCode);
        invoice.setInvoiceNum(invoiceNum);
        invoice.setTotalAmount(totalAmount);
        int i = invoiceMapper.updateById(invoice);
        if(i == 1){
            result.setMessage("update success");
            result.setCode(0);
        }else {
            result.setMessage("update error");
            result.setCode(1);
        }
        return result;
    }

}
